import { ref, computed } from 'vue'
import { DragOperationType, type DragOperationTypeValue } from './dragDrop'

// 拖拽操作接口
export interface DragOperation {
  id: string
  type: DragOperationTypeValue
  component: any
  target?: any
  previousState?: any
  newState?: any
  timestamp: number
  description: string
  metadata?: Record<string, any>
}

// 拖拽历史接口
export interface DragHistory {
  operations: DragOperation[]
  currentIndex: number
  maxHistory: number
}

// 历史管理类
export class HistoryManager {
  private history = ref<DragHistory>({
    operations: [],
    currentIndex: -1,
    maxHistory: 100
  })

  // 获取历史状态
  getHistory() {
    return this.history.value
  }

  // 记录操作
  recordOperation(operation: Omit<DragOperation, 'id' | 'timestamp'>) {
    const newOperation: DragOperation = {
      ...operation,
      id: this.generateOperationId(),
      timestamp: Date.now()
    }

    // 如果当前不在最新位置，删除当前位置之后的所有操作
    if (this.history.value.currentIndex < this.history.value.operations.length - 1) {
      this.history.value.operations = this.history.value.operations.slice(0, this.history.value.currentIndex + 1)
    }

    // 添加新操作
    this.history.value.operations.push(newOperation)

    // 限制历史记录数量
    if (this.history.value.operations.length > this.history.value.maxHistory) {
      this.history.value.operations.shift()
    } else {
      this.history.value.currentIndex++
    }

    return newOperation
  }

  // 撤销操作
  undoOperation(): DragOperation | null {
    if (this.history.value.currentIndex < 0) {
      return null
    }

    const operation = this.history.value.operations[this.history.value.currentIndex]
    this.history.value.currentIndex--
    return operation
  }

  // 重做操作
  redoOperation(): DragOperation | null {
    if (this.history.value.currentIndex >= this.history.value.operations.length - 1) {
      return null
    }

    this.history.value.currentIndex++
    return this.history.value.operations[this.history.value.currentIndex]
  }

  // 清空历史
  clearHistory() {
    this.history.value.operations = []
    this.history.value.currentIndex = -1
  }

  // 检查是否可以撤销
  canUndo(): boolean {
    return this.history.value.currentIndex >= 0
  }

  // 检查是否可以重做
  canRedo(): boolean {
    return this.history.value.currentIndex < this.history.value.operations.length - 1
  }

  // 获取历史统计信息
  getHistoryStats() {
    const { operations } = this.history.value
    const totalOperations = operations.length
    const operationTypeCounts = operations.reduce((counts, op) => {
      counts[op.type] = (counts[op.type] || 0) + 1
      return counts
    }, {} as Record<DragOperationTypeValue, number>)

    return {
      totalOperations,
      operationTypeCounts,
      currentIndex: this.history.value.currentIndex,
      maxHistory: this.history.value.maxHistory
    }
  }

  // 导出历史
  exportHistory(): string {
    const exportData = {
      history: this.history.value,
      exportTime: new Date().toISOString(),
      version: '1.0'
    }
    return JSON.stringify(exportData, null, 2)
  }

  // 导入历史
  importHistory(jsonData: string): boolean {
    try {
      const importData = JSON.parse(jsonData)
      if (importData.history && Array.isArray(importData.history.operations)) {
        this.history.value = importData.history
        return true
      }
      return false
    } catch (error) {
      console.error('导入历史记录失败:', error)
      return false
    }
  }

  // 设置最大历史记录数
  setMaxHistory(max: number) {
    this.history.value.maxHistory = Math.max(1, max)
    
    // 如果当前历史记录超过新的最大值，截断
    if (this.history.value.operations.length > this.history.value.maxHistory) {
      const excess = this.history.value.operations.length - this.history.value.maxHistory
      this.history.value.operations = this.history.value.operations.slice(excess)
      this.history.value.currentIndex = Math.max(-1, this.history.value.currentIndex - excess)
    }
  }

  // 生成操作ID
  private generateOperationId(): string {
    return `op_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  }
}

// 创建历史管理实例
export const historyManager = new HistoryManager()

// 组合式函数
export function useHistoryManager() {
  const history = computed(() => historyManager.getHistory())
  const canUndo = computed(() => historyManager.canUndo())
  const canRedo = computed(() => historyManager.canRedo())
  const historyStats = computed(() => historyManager.getHistoryStats())

  return {
    history,
    canUndo,
    canRedo,
    historyStats,
    recordOperation: historyManager.recordOperation.bind(historyManager),
    undoOperation: historyManager.undoOperation.bind(historyManager),
    redoOperation: historyManager.redoOperation.bind(historyManager),
    clearHistory: historyManager.clearHistory.bind(historyManager),
    exportHistory: historyManager.exportHistory.bind(historyManager),
    importHistory: historyManager.importHistory.bind(historyManager),
    setMaxHistory: historyManager.setMaxHistory.bind(historyManager)
  }
}
